﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace SysSUFront
{
    public partial class SettingsWindow : Form
    {
        public SettingsWindow()
        {
            InitializeComponent();
        }

        private void SettingsWindow_Load(object sender, EventArgs e)
        {
            tbxUCAddress.Text = Settings.Default.UbiCentreAddress;
            tbxUCPort.Text = Settings.Default.UbiCentrePort.ToString();
            tbxUBPort.Text = Settings.Default.UbiBrokerPort.ToString(); 
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            var messageError = String.Empty;
            if (String.IsNullOrEmpty(tbxUCAddress.Text) || !isValidIP(tbxUCAddress.Text))
                messageError += "Invalid UbiBroker address (IP number)\n";

            if (String.IsNullOrEmpty(tbxUCPort.Text) || !isValidPort(tbxUCPort.Text))
                messageError += "Invalid UbiBroker port (number)\n";

            if (String.IsNullOrEmpty(tbxUBPort.Text) || !isValidPort(tbxUBPort.Text))
                messageError += "Invalid UbiCentre port (number)";

            if (!messageError.Equals(String.Empty))
            {
                MessageBox.Show(messageError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Settings.Default.UbiCentreAddress = tbxUCAddress.Text;
            Settings.Default.UbiCentrePort = Int32.Parse(tbxUCPort.Text);
            Settings.Default.UbiBrokerPort = Int32.Parse(tbxUBPort.Text);

            Settings.Default.Save();

            Close();
        }

        private bool isValidIP(string addr)
        {
            var pattern = @"^(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|25[0-5]|2[0-4]\d)$";

            return String.IsNullOrEmpty(addr) ? false : new Regex(pattern).IsMatch(addr, 0);
        }

        private bool isValidPort(string port)
        {
            try
            {
                var number = Int32.Parse(port);
                return number >= 0 && number <= 65535;
            }
            catch
            {
                return false;
            }
        }
    }
}
